package com.ygsj;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.uhf.uhf.Common.Comm;
import com.ygsj.Utils.OkhttpUtils;
import com.ygsj.Utils.ParJson;
import com.ygsj.Utils.UHFUtils;
import com.ygsj.adapter.VehicleInfoAdapter;
import com.ygsj.ui.loader.Loader;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Response;
import qiu.niorgai.StatusBarCompat;

import static com.uhf.uhf.Common.Comm.isrun;
import static com.uhf.uhf.Common.Comm.lsTagList;
import static com.uhf.uhf.Common.Comm.lsTagList6B;
import static com.uhf.uhf.Common.Comm.tagListSize;

public class ConfirmActivity extends AppCompatActivity {
    private static final String TAG = "ConfirmActivity";
    private android.widget.TextView tv_header, tv_welcome, tv_state, tv_time;
    private android.widget.ListView lv_main;//展示请求内容界面
    private android.widget.Button btn_sure, btn_start, btn_stop,btn_list_cancel;
    private UHFUtils uhfUtils;
    private String strMsg = "";//handler中的消息;
    public long startTime;
    private ConstraintLayout con_content;//扫描界面显示
    private boolean networkAvailable;
    String CardID;
    private UpdatePopWindow popWindow;
    private String imei,userName_db,pwd;//userName_db为系统管理员的账号;
    List<VehicleInfoEntity> list_VehicleInfo;
    private VehicleInfoAdapter vehicleInfoAdapter;
    private String dbname,mmname,uuname;//mmname为站点名称,uuname为数据库返回的用户名;
    private String  name_person;//使用者的用户名;
    private int flag;//空车出场或者货场确认;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm);

        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#17a5e7"), 0);//状态栏系统蓝色,完全透明;
        // StatusBarCompat.translucentStatusBar(this,true);//透明状态栏,第二个参数,SDK >= 21时, 取消状态栏的阴影
        uhfUtils = UHFUtils.getInstance();
        initView();
        initData();
        networkAvailable = UHFUtils.getInstance().isNetworkAvailable(this);


    }

    /*生命周期重写*/
    @Override
    protected void onStart() {
        super.onStart();
        uhfUtils.InitDevice(this, connectH);
    }

    @Override
    protected void onStop() {
        super.onStop();
        uhfUtils.release();
    }

    /*橘黄色的大按钮,按一下就到了261,然后button_stop..这些键进行模拟点击*/
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (con_content.isShown()){//扫描界面显示与否
            if (event.getScanCode() == 261 && isrun)
                btn_stop.performClick();//模拟点击
            else if (event.getScanCode() == 261 && !isrun)
                btn_start.performClick();
        }else {
             if (event.getScanCode() == 261 && !isrun)
               btn_sure.performClick();
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        try {
            return super.dispatchKeyEvent(e);
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }


   /* 扫描键:点击开始扫描*/
    public void click_startscan(View view) {
        try {
            //startTimerTask();
            uhfUtils.clean();//清空数据
            tv_state.setText(R.string.read_state);
            // Awl.WakeLock();
            Comm.startScan();//扫描
            ReadHandleUI();//防止二次按键
            //CardID = uhfUtils.getEpcstr(this);
            /*时间流逝*/
            startTime = System.currentTimeMillis();
            handlerRunTime.postDelayed(runnable, 100);

        } catch (Exception ex) {
            Toast.makeText(ConfirmActivity.this,
                    "ERR：" + ex.getMessage(), Toast.LENGTH_SHORT)
                    .show();
        }

    }


    //点击停止扫描:停止的时候上传数据,请求后拉取listview展示;
    public void click_stopscan(View view) {
        tv_state.setText(R.string.stop_read_msg);
        Comm.stopScan();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        handlerRunTime.removeCallbacks(runnable);//时间停流
        StopHandleUI();//可以点击开始按钮;
        if (networkAvailable) {
            Loader.showLoading(this);
            if (CardID == null ){//如果没有刷卡就点击停止,则直接吐司
                Loader.stopLoading();
                Toast.makeText(ConfirmActivity.this, "没有刷卡或无效卡", Toast.LENGTH_SHORT).show();
                CardID = null;
            }else {
                if (flag == GloableUrl.YARD_CONFIRM){//货场确认;
                    getCardInfo();//传参并从服务器获取网络数据;
                }else if (flag == GloableUrl.EMPTY_OUT ){//空车出场;
                    emptyOut();
                }

            }

        } else {
            Toast.makeText(this, "请检查网络", Toast.LENGTH_SHORT).show();
        }


    }


    /*点击确定按钮,确认后上传Tag*/
    public void click_upload(View view) {
        popWindow = new UpdatePopWindow(ConfirmActivity.this);
        popWindow.showPopupWindow(con_content); //展示popwindow,正在上传数据;

        upLoadTag();//网络上传Tag标志;
        tv_header.setText("货场确认");
    }

    /*确认上传Tag*/
    private void upLoadTag() {
        FormBody.Builder builder = new FormBody.Builder();
        /*if (!TextUtils.isEmpty(CardID))builder.add("icCode",CardID);
        if (!TextUtils.isEmpty(imei))builder.add("MacCode",imei);
        if (!TextUtils.isEmpty(dbname)) builder.add("dbname",dbname);
        if (!TextUtils.isEmpty(userName_db))builder.add("username",userName_db);
        if (!TextUtils.isEmpty(pwd)) builder.add("password",pwd);
        if (!TextUtils.isEmpty(name))builder.add("name",name);*/


         builder.add("icCode",CardID);
         builder.add("MacCode",imei);
         builder.add("dbname",dbname);
         builder.add("username", userName_db);
         builder.add("password",pwd);
         builder.add("name",name_person);
        OkhttpUtils.post_GetJson(GloableUrl.update, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(ConfirmActivity.this, "" +
                                    "请检查网络或联系管理员", Toast.LENGTH_SHORT).show();
                        }
                    });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                    String json = response.body().string();
                    Log.e("upload", "onResponse: "+json);
                    String flag =  ParJson.upDateInfo(json);

                    final String msg = ParJson.upDateInfoMsg(json);
                if (!TextUtils.isEmpty(flag)) {
                    if (flag.equals("0")){
                        Message message = Message.obtain();
                        message.what = 3;
                        handlerNet.sendMessage(message);
                    } else  {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                popWindow.dismiss();
                                Loader.stopLoading();
                                if (!TextUtils.isEmpty(msg))Toast.makeText(ConfirmActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            popWindow.dismiss();
                            Loader.stopLoading();
                            if (!TextUtils.isEmpty(msg))Toast.makeText(ConfirmActivity.this,
                                    "服务器连接失败,请联系管理员", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        },builder);



    }
    /*开始扫描的UI变化*/
    private void ReadHandleUI() {
        this.btn_start.setEnabled(false);
        this.btn_stop.setEnabled(true);
    }

    /*停止扫描的UI变化*/
    private void StopHandleUI() {
        btn_start.setEnabled(true);
        btn_stop.setEnabled(false);
    }


    /*以下各种异步请求的handler*/
    //请求网络数据的handler
    Handler handlerNet = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1://刷卡无返回无数据的情况
                    Loader.stopLoading();
                    Toast.makeText(ConfirmActivity.this, "上传数据失败,请检查网络", Toast.LENGTH_SHORT).show();
                   // tv_welcome.setText((String) msg.obj);
                   CardID = null;//重要,否则会错刷卡或者状态无法改变;
                    break;
                case 2://点击停止btn,有cardid的情况,返回有数据listview展示
                    Loader.stopLoading();
                    tv_welcome.setText("查询成功...查询成功...查询成功...查询成功...查询成功...");
                    if (!TextUtils.isEmpty(CardID)) tv_header.setText("查询列表");

                    con_content.setVisibility(View.GONE);//扫面界面消失
                    btn_start.setEnabled(false);//扫描键不可点击
                    btn_stop.setEnabled(false);//停止键不可点击;
                    /*拿到listview界面并显示*/
                    list_VehicleInfo = (List<VehicleInfoEntity>) msg.obj;
                    vehicleInfoAdapter = new VehicleInfoAdapter(ConfirmActivity.this);
                    if (list_VehicleInfo!=null) vehicleInfoAdapter.setData(list_VehicleInfo);
                    lv_main.setAdapter(vehicleInfoAdapter);
                    lv_main.setVisibility(View.VISIBLE);
                    btn_sure.setVisibility(View.VISIBLE);//确定按钮显示;
                    btn_list_cancel.setVisibility(View.VISIBLE);
                    //CardID = null;//不能设置为null,联系到后面的确认;
                    break;
                case 3://点击确定上传btn
                    //清空listview数据
                    clearListview();

                    lv_main.setVisibility(View.GONE);//listview消失
                    btn_sure.setVisibility(View.INVISIBLE);//最底下button消失;
                    btn_list_cancel.setVisibility(View.INVISIBLE);
                    con_content.setVisibility(View.VISIBLE);//扫描界面出现
                    Toast.makeText(ConfirmActivity.this, "上传成功", Toast.LENGTH_SHORT).show();

                    if (con_content.isShown()){
                         popWindow.dismiss();//pop消失
                    }
                    btn_start.setEnabled(true);//扫描可用
                    btn_stop.setEnabled(true);//停止可用
                    /*重新扫描界面状态*/
                    tv_state.setText("准备扫描");
                    tv_time.setText("...");
                    tv_welcome.setText(R.string.welcome);
                    CardID = null;//重要,否则会错刷卡或者状态无法改变;
                    break;

                default:
                    break;
            }
        }
    };


    //connectH为用于异步处理连接返回的数据
    @SuppressLint("HandlerLeak")
    public Handler connectH = new Handler() {
        @SuppressLint("SetTextI18n")
        @SuppressWarnings({"unchecked", "unused"})
        @Override
        public void handleMessage(Message msg) {

            try {
                if (Comm.moduleType == Comm.Module.UHF005) {
                    //Toast.makeText(ConfirmActivity.this, "6bTag", Toast.LENGTH_SHORT).show();
                    //Log.e("6bTag", "this is 6Tag");
                } else {
                    /*以下设置功率与模式*/
                    Comm.mOtherHandler = opeHandler;//测试用
                    // Comm.opeT = setReg;
                    Comm.setAntReg(0);//频率区域设置为中国;
                    // Comm.opeT = Comm.operateType.setSession;
                    Comm.setSes(1);//session设置为Session1,相关说明在资料的文档中;
                    //Comm.opeT = Comm.operateType.setPower;
                    Comm.setAntPower(0, 0, 0, 0);
                }

                Comm.mInventoryHandler = uhfhandler;//读取卡信息;

                Bundle bd = msg.getData();
                strMsg = bd.get("Msg").toString();
                if (!TextUtils.isEmpty(strMsg)) {
                   // Toast.makeText(ConfirmActivity.this, R.string.device_msg_success, Toast.LENGTH_SHORT).show();
                    //Comm.SetInventoryTid(true);
                    Log.e("main", "initDevice"+R.string.device_msg_success);
                } else {
                    Toast.makeText(ConfirmActivity.this, R.string.device_msg, Toast.LENGTH_SHORT).show();
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    //扫描后异步处理刷卡的数量
    @SuppressLint("HandlerLeak")
    public Handler uhfhandler = new Handler() {
        @SuppressLint({"DefaultLocale", "SetTextI18n"})
        @SuppressWarnings({"unchecked", "unused"})
        @Override
        public void handleMessage(Message msg) {
            try {
                if (Comm.is6BTag)
                    Comm.tagListSize = lsTagList6B.size();
                else
                    tagListSize = lsTagList.size();
                Bundle bd = msg.getData();
                int readCount = bd.getInt("readCount");
                if (tagListSize > 0) {
                    CardID = uhfUtils.getEpcstr(ConfirmActivity.this);//获取卡号,最重要的;
                    tv_state.setText(CardID);
                    Log.e(TAG, "handleMessage: "+CardID );
                }
                if (readCount > 1) {
                    Toast.makeText(ConfirmActivity.this, "请勿重复刷卡", Toast.LENGTH_SHORT).show();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    /*两次回退键退出app*/
    private boolean canExit = false;

    @Override
    public void finish() {
        if (canExit) {
            uhfUtils.release();
            startActivity(new Intent(ConfirmActivity.this,LoginActivity.class));
            System.exit(0);
            super.finish();

        } else {
            Toast.makeText(ConfirmActivity.this, "再次按键退出程序", Toast.LENGTH_SHORT).show();
            canExit = true;
            handlerRunTime.postDelayed(new Runnable() {
                @Override
                public void run() {
                    canExit = false;
                }
            }, 2000);
        }
    }


    private void initData() {
        imei = uhfUtils.getIMEI(this);//获取imei;
        userName_db = getIntent().getStringExtra("userName");
        pwd = getIntent().getStringExtra("pwd");
        dbname = getIntent().getStringExtra("dbname");
        name_person = getIntent().getStringExtra("name");
        mmname = getIntent().getStringExtra("mmname");
        uuname = getIntent().getStringExtra("uuname");
        flag = getIntent().getIntExtra("flag",1);
        if (flag == GloableUrl.YARD_CONFIRM){
            tv_header.setText("货场确认");
        }else if (flag == GloableUrl.EMPTY_OUT){
            tv_header.setText("空车出场");
        }
        Log.e("user_db", "user_db "+userName_db );
        Log.e("name_person", "name_p: "+name_person );
    }

    private void initView() {
        btn_sure = findViewById(R.id.btn_sure);
        lv_main = findViewById(R.id.lv_main);
        tv_welcome = findViewById(R.id.tv_welcome);
        tv_header = findViewById(R.id.tv_main_header);//发货确认,收货确认
        btn_list_cancel = findViewById(R.id.btn_list_cancel);
        btn_start = findViewById(R.id.btn_yardConfirm);
        btn_stop = findViewById(R.id.btn_stop);
        tv_state = findViewById(R.id.tv_state);
        con_content = findViewById(R.id.con_content);
        btn_sure.setVisibility(View.INVISIBLE);
        btn_list_cancel.setVisibility(View.INVISIBLE);
        tv_time = findViewById(R.id.tv_time);

    }

    private void emptyOut() {
        FormBody.Builder builder = new FormBody.Builder();
        if (CardID!=null)builder.add("icCode", CardID);
        if (imei!=null) builder.add("MacCode", imei);
        builder.add("dbname",dbname);
        builder.add("username", userName_db);
        builder.add("password",pwd);
        builder.add("name",name_person);
        OkhttpUtils.post_GetJson(GloableUrl.updateForced, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Loader.stopLoading();
                        }
                    });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();

               Log.e(TAG, "onResponse: "+json);

                final String msg_emptyout = ParJson.getCardInfoMsg(json);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Loader.stopLoading();
                        Toast.makeText(ConfirmActivity.this, msg_emptyout, Toast.LENGTH_SHORT).show();
                        tv_state.setText(msg_emptyout);
                        CardID = null;
                    }
                });
            }
        },builder);


    }



    /*网络获取数据*/
    public void getCardInfo() {
        FormBody.Builder builder = new FormBody.Builder();
       if (CardID!=null)builder.add("icCode", CardID);
        Log.e("main", "getCardInfo: "+CardID);
       if (imei!=null) builder.add("MacCode", imei);
       builder.add("username", userName_db);
       builder.add("password",pwd);
       builder.add("dbname",dbname);

        OkhttpUtils.post_GetJson(GloableUrl.confirm, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ConfirmActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                String flag  = ParJson.getCardInfoFlag(json);
                final String msg  = ParJson.getCardInfoMsg(json);
                if (!TextUtils.isEmpty(flag)) {
                    if (flag.equals("6")||flag.equals("7")){
                        List<VehicleInfoEntity> list = ParJson.getCardInfo(json);
                        Message message = handlerNet.obtainMessage();
                        message.obj = list;
                        message.what = 2;
                        handlerNet.sendMessage(message);
                    }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (!TextUtils.isEmpty(msg)){
                                        tv_state.setText(msg);
                                        Toast.makeText(ConfirmActivity.this, msg, Toast.LENGTH_SHORT).show();
                                        Loader.stopLoading();
                                        CardID = null;//重要,否则会错刷卡或者状态无法改变;
                                    }
                                }
                            });
                    }
                }else {//没有请求到数据的处理
                    Message message = handlerNet.obtainMessage();
                    message.what = 1;
                    handlerNet.sendMessage(message);
                }
            }
        },builder);


    }

    Handler handlerRunTime = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handlerRunTime.postDelayed(this, 0);//this指的是runnable,延迟0秒执行,可以实现定时器的效果;
            long nowTime = System.currentTimeMillis();
            long runTime = nowTime - startTime;//startTime点击开始执行
            long totalSeconds = runTime / 1000;
            //求出现在的毫秒
            long currentSss = (runTime % 1000);//点击数耗费的毫秒数;
            String mRunTime = String.valueOf(totalSeconds) + "." + String.valueOf(currentSss) + "s";
            tv_time.setText(mRunTime);
        }
    };

    private Handler opeHandler = new Handler() {

        public void handleMessage(Message msg) {//设置完session与功率后返回的flag
            Bundle b = msg.getData();

            boolean isSetReg = b.getBoolean("isSetReg");
            // if (isSetReg) Log.e("lan", "设置范围 success");

            boolean isSetSes = b.getBoolean("isSetSes");
            //if (isSetSes)  Log.e("session", "设置会话 success");

            boolean isSetPower = b.getBoolean("isSetPower");
            // if (isSetPower)  Log.e("power", "设置功率 success");

        }
    };


    /*public void click_regist(View view) {
        Intent intent = new Intent(ConfirmActivity.this,SignUpActivity.class);
        intent.putExtra("userName", userName_db);
        intent.putExtra("pwd",pwd);
        intent.putExtra("imei",imei);
        intent.putExtra("dbname",dbname);
        startActivity(intent);
    }*/

    public void click_list_cancel(View view) {
        listCancel();
    }

    private void listCancel() {
        clearListview();
        lv_main.setVisibility(View.GONE);//listview消失
        btn_sure.setVisibility(View.INVISIBLE);//最底下button消失;
        btn_list_cancel.setVisibility(View.INVISIBLE);
        con_content.setVisibility(View.VISIBLE);//扫描界面出现
        btn_start.setEnabled(true);//扫描可用
        btn_stop.setEnabled(true);//停止可用
        tv_state.setText("准备扫描");
        tv_time.setText("...");
        tv_welcome.setText(R.string.welcome);
        tv_header.setText("货场确认");
        CardID = null;
    }

    private void clearListview() {
        if(list_VehicleInfo.size() > 0){
            list_VehicleInfo.removeAll(list_VehicleInfo);
            vehicleInfoAdapter.notifyDataSetChanged();
            lv_main.setAdapter(vehicleInfoAdapter);
        }
    }

    public void click_back(View view) {
        if (lv_main.isShown()){
            listCancel();
        }else {
            Intent intent2 = new Intent(ConfirmActivity.this,MainActivity.class);
            addExtra(intent2);
            startActivity(intent2);
            super.finish();
        }

    }

    public void  addExtra(Intent intent){
        intent.putExtra("userName", userName_db);
        intent.putExtra("pwd",pwd);
        intent.putExtra("dbname",dbname);
        intent.putExtra("name",name_person);
        intent.putExtra("mmname",mmname);
        intent.putExtra("uuname",uuname);
        intent.putExtra("imei",imei);
    }
}
